#include "ZLoadingControl.h"
#include "ZControlFactory.h"

namespace ZuiLib
{


ZLoadingControl::ZLoadingControl()
	:m_duration(800),m_frameCount(8),m_startTime(0),m_isAnimation(false),m_rotation(0),m_autoStart(false)
{
}

ZLoadingControl::~ZLoadingControl()
{

}

const char* ZLoadingControl::GetClass() const
{
	return "ZLoadingControl";
}
void* ZLoadingControl::GetInterface(const char* pstrName)
{
	if (strcmp(pstrName,"ZLoadingControl")==0)
		return this;
	else
		return ZControl::GetInterface(pstrName);
}

void ZLoadingControl::DoInit()
{
	if (m_autoStart)
	{
		StartAnimation();
	}
}

void ZLoadingControl::SetAutoStart(bool autostart) {
	m_autoStart = autostart;
}

void ZLoadingControl::StartAnimation()
{
	if (m_isAnimation)
		return;
	m_isAnimation=true;
	m_startTime=ZGetTickCount();
	Schedule(schedule_selector(ZLoadingControl::UpdateFrame),
		m_duration/m_frameCount,m_duration/m_frameCount);
}

void ZLoadingControl::StopAnimation()
{
	if (!m_isAnimation)
		return;
	Unschedule(schedule_selector(ZLoadingControl::UpdateFrame));
	m_isAnimation=false;
}

bool ZLoadingControl::IsAnimating()
{
	return m_isAnimation;
}

void ZLoadingControl::SetImage(const char* img)
{
	m_image=img;
}

void ZLoadingControl::SetCycleFrameCount(Uint32 count)
{
	m_frameCount=count;
}

void ZLoadingControl::SetCycleTime(Uint32 ms)
{
	m_duration=ms;
}

void ZLoadingControl::UpdateFrame(Uint32 dt)
{
	Uint32 curFrame=(dt-m_startTime)%m_duration * m_frameCount/ m_duration;
	m_rotation=curFrame*360/m_frameCount;
	Invalidate();
}

void ZLoadingControl::PaintStatusImage(ZRenderer* hDC)
{
	m_image.rotate = m_rotation;
	DrawImage(hDC,&m_image);
}

void ZLoadingControl::SetAttribute(const char* pstrName, const char* pstrValue)
{
	if (stricmp(pstrName,"image")==0)
	{
		SetImage(pstrValue);
	}
	else if (stricmp(pstrName,"framecount")==0)
	{
		SetCycleFrameCount(atoi(pstrValue));
	}
	else if (stricmp(pstrName,"cycletime")==0)
	{
		SetCycleTime(atoi(pstrValue));
	}
	else if (stricmp(pstrName,"autostart")==0)
	{
		m_autoStart= stricmp(pstrValue,"true")==0;
	}
	else
		ZControl::SetAttribute(pstrName,pstrValue);
}











}



